package ext.tianma.part.processors;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.ptc.core.components.beans.ObjectBean;
import com.ptc.core.components.forms.DefaultObjectFormProcessor;
import com.ptc.core.components.forms.FormProcessingStatus;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.forms.FormResultAction;
import com.ptc.core.meta.common.TypeIdentifier;
import com.ptc.core.meta.common.TypeIdentifierHelper;
import com.ptc.netmarkets.util.beans.NmCommandBean;
import com.ptc.windchill.enterprise.copy.server.CoreMetaUtility;

import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.tianma.bom.util.EnumerationUtil;
import ext.tianma.part.MyPartUtil;
import ext.tianma.part.imported.CusImportBOM;
import ext.tianma.part.imported.ImportedExcelUtil;
import wt.content.ApplicationData;
import wt.content.ContentRoleType;
import wt.content.ContentServerHelper;
import wt.doc.WTDocument;
import wt.fc.Link;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.collections.WTValuedHashMap;
import wt.folder.Folder;
import wt.folder.FolderHelper;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.State;
import wt.log4j.LogR;
import wt.part.WTPart;
import wt.part.WTPartDescribeLink;
import wt.part.WTPartHelper;
import wt.query.KeywordExpression;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionServerHelper;
import wt.util.WTException;

public class ImportHistoryDocumentProcessors extends DefaultObjectFormProcessor {
	private static final String CLASSNAME = CusImportBOM.class.getName();
	private static final String TIANMA_CONTROLDOCUMENT = "cn.tianma.ControlDocument";//受控PDF图纸
	private static final String TIANMA_ProcessDocuments = "cn.tianma.ProcessDocuments";//工艺文件
	private static String errorMessage = "";
	private static Logger logger = LogR.getLogger(ImportHistoryDocumentProcessors.class.getName());
	SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static List<String> typelist = new ArrayList<String>();
	
	static{
		try {
			typelist = EnumerationUtil.getTypeLegalValues("cn.tianma.ProcessDocuments", "SmallDocType");
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	public FormResult doOperation(NmCommandBean nmCommandBean, List list) throws WTException {
		logger.debug("start import===>>>");
		FormResult formresult = new FormResult();
		String strMsg = "";
		HttpServletRequest request = nmCommandBean.getRequest();
		if (request != null) {
			String[] parameter = request.getParameterValues("fileUrl");
			if (parameter == null) {
				return formresult;
			}
			String textName = parameter[0];

			if (textName != null) {
				// 判断是否为Excel文件类型
				if (!textName.endsWith(".xls") && !textName.endsWith(".xlsx")) {
					throw new WTException("选择的文件必须是Excel格式的文件");
				}

			}
			File file = (File) request.getAttribute("fileUrl");

			if (file != null) {
				String fileNumber = file.getAbsolutePath();

				if (StringUtils.isNotEmpty(fileNumber)) {
					FileInputStream fis = null;
					Workbook wb = null;
					boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
					StringBuffer strBuf = new StringBuffer();
					try {
						fis = new FileInputStream(fileNumber);
						// 根据Excel文件的格式判断文件的解释方式为03或07（解析Excel兼容性）
						if (textName.endsWith(".xls")) {
							wb = new HSSFWorkbook(fis);
						} else if (textName.endsWith(".xlsx")) {
							wb = new XSSFWorkbook(fis);
						}
						Sheet sheet = wb.getSheetAt(0);
						if (sheet != null) {
							importHistoryDocuments(sheet, strBuf);
							logger.debug("start  导入==>>>" + strMsg);
						}

					} catch (IOException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						errorMessage = strBuf.toString();
						logger.debug("Debug   logs:");
						SessionServerHelper.manager.setAccessEnforced(flag);
					}
					if (strBuf.length() > 0) {
						logger.debug("Update Part Error : " + strBuf.toString());
						// throw new WTException("请根据错误信息检查导入数据");
					} else {
						logger.debug("==========>>>start import sucessful<<<=============");
					}
				}
			}
		}

		return formresult;
	}

	@Override
	public FormResult setResultNextAction(FormResult paramFormResult, NmCommandBean paramNmCommandBean,
			List<ObjectBean> paramList) throws WTException {
		logger.debug("start  message====>>>>" + errorMessage);
		FormResult formResult = super.setResultNextAction(paramFormResult, paramNmCommandBean, paramList);

		if (formResult.getStatus().equals(FormProcessingStatus.SUCCESS)) {
			String result = "";
			if (errorMessage.length() > 0) {
				result = errorMessage;
				logger.debug("错误====—>>>" + result);
				result = result.toString();
				formResult.setStatus(FormProcessingStatus.FAILURE);
				result = "<ul >" + result + "</ul>";
				result = "document.getElementById(\"CHECK_RESULT\").innerHTML=\"" + result + "\";alert(\"检测结果已出，请查看\")";
				formResult.setNextAction(FormResultAction.JAVASCRIPT);
				formResult.setJavascript(result);
			} else {
				formResult.setNextAction(FormResultAction.REFRESH_OPENER_AND_SUBMIT_IFRAMES);
			}
		}
		return formResult;
	}

	/***
	 * 导入bom方法
	 * 
	 * @param sheet
	 *            sheet页
	 * @param strBuf
	 *            返回错误信息
	 * @return
	 * @throws Exception
	 */
	private static String importHistoryDocuments(Sheet sheet, StringBuffer strBuf) {
		String strMesg = "";
		Map<Integer, String> headMap = getHeader(sheet);
		List<String> partInfoabc = new ArrayList<String>();
		List<WTPart> checkInPartList = new ArrayList<WTPart>();
		Iterator<Row> rowIterator = sheet.rowIterator();

		while (rowIterator.hasNext()) {
			Row row = rowIterator.next();
			logger.debug("start 3======>>>" + row);
			if (row != null) {
				int rowNumber = row.getRowNum();
				int rowNumberRow = rowNumber + 1;
				logger.debug("Start Process Row " + rowNumberRow);
				if (rowNumber > 0) {// && rowNumber <= rowNum
					if (headMap != null) {
						logger.debug("headMap==>>" + headMap);
						strMesg = importHistoryDocument(row, headMap, strBuf, checkInPartList, rowNumberRow,
								partInfoabc);
					}
				}
				logger.debug("End Process Row " + rowNumberRow);
			}
		}
		return strMesg;
	}

	/***
	 * 导入BOM逻辑方法
	 * 
	 * @param row
	 *            excel行
	 * @param headMap
	 *            列名称map
	 * @param strBuf
	 *            错误信息
	 * @param checkInPartList
	 *            存放检出对象
	 * @param rowNumberRow
	 *            行号
	 * @param partInfoabc
	 *            判断是否重复名称
	 * @return
	 * @throws Exception
	 */
	private static String importHistoryDocument(Row row, Map<Integer, String> headMap, StringBuffer strBuf,
			List<WTPart> checkInPartList, int rowNumberRow, List<String> partInfoabc) {
		boolean access = SessionServerHelper.manager.setAccessEnforced(false);
		String strMesg = "";
		// Transaction trx = new Transaction();
		try {
			// trx.start();
			String documentName = ""; // 文档名称
			String docType = "";// 文档类型
			String savePath = ""; // 存储路径
			String attachmentPath = ""; // 主要内容路径
			String context = "";// 上下文
			String associatedPart = ""; // 关联料号
			String SmallDocType = "";//文档小类
			String otherPart = "";

			Iterator<Cell> cellIterator = row.cellIterator();
			while (cellIterator.hasNext()) {
				Cell cell = cellIterator.next();
				if (cell != null) {
					int columnIndex = cell.getColumnIndex();
					String head = headMap.get(columnIndex);
					if (head == null || head.trim().isEmpty()) {
						continue;
					}
					if (head.equals("文档名称")) {
						documentName = ImportedExcelUtil.getCellValueAsString(cell).trim();
					} else if (head.equals("文档类型")) {
						docType = ImportedExcelUtil.getCellValueAsString(cell).trim();
					} else if (head.equals("存储路径")) {
						savePath = ImportedExcelUtil.getCellValueAsString(cell).trim();
					} else if (head.equals("主要内容名称")) {
						attachmentPath = ImportedExcelUtil.getCellValueAsString(cell).trim();
					} else if (head.equals("上下文")) {
						context = ImportedExcelUtil.getCellValueAsString(cell, true).trim();
					} else if (head.equals("关联料号")) {
						associatedPart = ImportedExcelUtil.getCellValueAsString(cell, true).trim();
					} else if (head.equals("文档小类")) {
						SmallDocType = ImportedExcelUtil.getCellValueAsString(cell, true).trim();
					}else if (head.equals("其他料号")) {
						otherPart = ImportedExcelUtil.getCellValueAsString(cell, true).trim();
					}


				}
			}

			WTContainer wtContainer = null;
			// WTPart part = null;
			List<WTPart> list = new ArrayList();
			TypeIdentifier docTypeId = null;
			// 获取上下文
			WTContainerRef containerRef = null;
			Hashtable updateIBAValues = new Hashtable();
			//工艺文档
			Hashtable updateIBAValues2 = new Hashtable();
			if (StringUtils.isEmpty(documentName)) {
				strMesg = strBuf.append("<li>第" + rowNumberRow + "行,文档名称为空！") + "</li>".toString();
			} else {
				if (partInfoabc.contains(documentName)) {

					strMesg = strBuf.append("<li>第" + rowNumberRow + "行,存在重复数据，文档名称为 " + documentName)
							+ "</li>".toString();
				} else {
					partInfoabc.add(documentName);
				}
			}

			if (StringUtils.isEmpty(docType)) {
				strMesg = strBuf.append("<li>第" + rowNumberRow + "行,文档类型为空！") + "</li>".toString();
			} else {
				//文档类小类
				updateIBAValues2.put("SmallDocType", SmallDocType);
				// 获取文档类型
				docTypeId = TypeIdentifierHelper.getTypeIdentifier(docType);
				if (docTypeId == null) {
					strMesg = strBuf.append("<li>第" + rowNumberRow + "行,文档类型不存在！") + "</li>".toString();
				}else if(docType.indexOf(TIANMA_ProcessDocuments)!=-1 && StringUtils.isEmpty(SmallDocType)){
					strMesg = strBuf.append("<li>第" + rowNumberRow + "行为工艺文件,文档小类不能为空！") + "</li>".toString();
				}else if(docType.indexOf(TIANMA_ProcessDocuments)!=-1 
						&& !StringUtils.isEmpty(SmallDocType)
						&& !typelist.contains(SmallDocType.trim())){
					strMesg = strBuf.append("<li>第" + rowNumberRow + "行为工艺文件,文档小类值不在指定范围！") + "</li>".toString();
				}
			}

			if (StringUtils.isEmpty(savePath)) {
				strMesg += strBuf.append("<li>第" + rowNumberRow + "行,存储路径为空！") + "</li>".toString();
			}

			if (StringUtils.isEmpty(attachmentPath)) {
				strMesg += strBuf.append("<li>第" + rowNumberRow + "行,主要内容名称为空！") + "</li>".toString();
			} else {
				File file = new File(attachmentPath);
				System.out.println("===attachmentPath:"+attachmentPath);
				System.out.println("===attachmentPath exist:"+file.exists());
				if (!file.exists())
					strMesg += strBuf.append("<li>第" + rowNumberRow + "行,主要内容不存在！") + "</li>".toString();
			}

			if (StringUtils.isEmpty(context)) {
				strMesg += strBuf.append("<li>第" + rowNumberRow + "行,上下文为空！") + "</li>".toString();
			} else {
				wtContainer = getContainer(context);
				if (wtContainer != null) {
					containerRef = WTContainerRef.newWTContainerRef(wtContainer);
					if (containerRef == null) {
						strMesg += strBuf.append("<li>第" + rowNumberRow + "行," + context + "上下文不存在！")
								+ "</li>".toString();
					}
				} else {
					strMesg += strBuf.append("<li>第" + rowNumberRow + "行," + context + "上下文不存在！") + "</li>".toString();
				}

			}

			if (StringUtils.isEmpty(associatedPart)) {
				strMesg += strBuf.append("<li>第" + rowNumberRow + "行,关联料号为空！") + "</li>".toString();
			} else {
				updateIBAValues.put("Item", associatedPart);
				// part = PartUtil.getWTPartByNumber(associatedPart);
				list = getAllLatestVersionPart(associatedPart);
				if (list.size() > 0) {
					for (WTPart part : list) {
						String viewName = part.getViewName();
						QueryResult qr = WTPartHelper.service.getDescribedByWTDocuments(part, false);
						if ((qr != null) && (qr.size() > 0)) {
							strMesg += strBuf.append("<li>第" + rowNumberRow + "行,视图产地为" + viewName + "的"
									+ associatedPart + "物料已存在相关受控文档！") + "</li>".toString();
						}
					}
				} else {
					strMesg += strBuf.append("<li>第" + rowNumberRow + "行," + associatedPart + "物料不存在！")
							+ "</li>".toString();
				}

			}

			if (StringUtils.isEmpty(strMesg)) {
				// 新建一个文档对象
				WTDocument doc = WTDocument.newWTDocument();
				// 给文档对象设置类型
				doc = (WTDocument) CoreMetaUtility.setType(doc, docTypeId);
				// 设置文档名称
				doc.setName(documentName);
				// 设置上下文
				doc.setContainerReference(containerRef);
				// 设置文件夹
				Folder location = null;
				// 查询文件夹是否存在
				try {
					location = FolderHelper.service.getFolder(savePath, containerRef);
				} catch (Exception e) {
					location = null;
				}
				// 若文件夹不存在，则创建该文件夹
				if (location == null)
					location = FolderHelper.service.saveFolderPath(savePath, containerRef);
				// 设置文件夹到Doc对象
				if (location != null) {
					WTValuedHashMap map = new WTValuedHashMap();
					map.put(doc, location);
					FolderHelper.assignLocations(map);
				}
				if ("cn.tianma.ControlDocument".equals(docType)) {
					doc = (WTDocument) IBAUtil.forceSetIBAValues(doc, updateIBAValues);// 设置测试料号扩展属性
				}else if(TIANMA_ProcessDocuments.equals(docType)){
					doc = (WTDocument) IBAUtil.forceSetIBAValues(doc, updateIBAValues2);// 设置文档类小类属性
				}
				doc = (WTDocument) PersistenceHelper.manager.save(doc);
				doc = (WTDocument) PersistenceHelper.manager.refresh(doc);
				// set primary content

				if (attachmentPath != null) {
					ApplicationData applicationdata = ApplicationData.newApplicationData(doc);
					applicationdata.setRole(ContentRoleType.PRIMARY);
					if (attachmentPath instanceof String) {
						String filePath = (String) attachmentPath;
						ContentServerHelper.service.updateContent(doc, applicationdata, filePath);
					}

				}

				// 设置文档状态（已发布）
				// State state = State.toState("RELEASED");
				// System.out.println(state.getDisplay());
				// System.out.println(state.getDisplay(Locale.CHINA));
				// LifeCycleState cycleState =
				// LifeCycleState.newLifeCycleState();
				// cycleState.setState(state);
				// doc.setState(cycleState);

				PersistenceServerHelper.manager.update(doc);
				LifeCycleHelper.service.setLifeCycleState(doc, State.toState("RELEASED"), true);// 设置状态为已发布
				doc = (WTDocument) PersistenceHelper.manager.refresh(doc);
				// if (!WorkflowUtil.isObjectCheckedOut(part)) {// 部件不检出的话，自动检出
				// part = (WTPart) CoreUtil.checkoutObject(part);// 检出部件
				// }
				// if (!checkInPartList.contains(part)) {// 将检出的部件存放在list中
				// checkInPartList.add(part);
				// }
				for (WTPart part : list) {
					Link link = (Link) WTPartDescribeLink.newWTPartDescribeLink(part, doc);
					PersistenceServerHelper.manager.insert(link);
				}
				
				//OD工藝文件特殊處理
				
				if (otherPart != null) {
					if(otherPart.contains("；")) {
						String[] strArray = otherPart.split("；");
				        for (int i = 0; i < strArray.length; i++) {
				            System.out.println(i+":" + strArray[i]);
				            String strPartNumber = strArray[i];
				            System.out.println("strPartNumber===>>"+strPartNumber);
				         
				            List<WTPart> OdPartlist = getAllLatestVersionPart(strPartNumber);
							if (OdPartlist.size() > 0) {
								for (WTPart part : OdPartlist) {
									String viewName = part.getViewName();
									QueryResult qr = WTPartHelper.service.getDescribedByWTDocuments(part, false);
									if ((qr != null) && (qr.size() > 0)) {
										strMesg += strBuf.append("<li>第" + rowNumberRow + "行,视图产地为" + viewName + "的"
												+ associatedPart + "物料已存在相关受控文档！") + "</li>".toString();
									}
								}
							} else {
								strMesg += strBuf.append("<li>第" + rowNumberRow + "行," + associatedPart + "物料不存在！")
										+ "</li>".toString();
							}

							for (WTPart parts : OdPartlist) {
								Link link = (Link) WTPartDescribeLink.newWTPartDescribeLink(parts, doc);
								PersistenceServerHelper.manager.insert(link);
							}
				        }
					}
				}
				// trx.commit();
				// trx = null;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// if (trx != null) {
			// trx.rollback();
			// }
			SessionServerHelper.manager.setAccessEnforced(access);
		}

		return strMesg;
	}

	/**
	 * 检入已检出的
	 * 
	 * @param outPart
	 */
	private static void checkinWTPart(List<WTPart> outPart) {
		if (outPart != null) {
			for (int i = 0; i < outPart.size(); i++) {
				WTPart inPart = outPart.get(i);
				if (inPart != null) {
					try {
						CoreUtil.checkinObject(inPart, "导入历史文档成功后，检入部件。");
					} catch (WTException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * 获取excel表头
	 * 
	 * @param sheet
	 * @return
	 */
	private static Map<Integer, String> getHeader(Sheet sheet) {
		Map<Integer, String> headerMap = new HashMap<Integer, String>();
		Row row = sheet.getRow(0);
		if (row != null) {
			Iterator<Cell> iterator = row.cellIterator();
			while (iterator.hasNext()) {
				Cell cell = iterator.next();
				String header = ImportedExcelUtil.getCellValueAsString(cell).trim();
				Integer columnIndex = cell.getColumnIndex();
				if (header != null && !header.trim().isEmpty()) {
					headerMap.put(columnIndex, header);
				}
			}
		}
		return headerMap;
	}

	/**
	 * 根据名称获取上下文
	 * 
	 * @param s
	 * @return
	 * @throws QueryException
	 * @throws WTException
	 */
	public static WTContainer getContainer(String s) throws wt.query.QueryException, wt.util.WTException {
		QuerySpec queryspec = new QuerySpec(WTContainer.class);
		queryspec.appendSearchCondition(
				new SearchCondition(WTContainer.class, WTContainer.NAME, SearchCondition.EQUAL, s));
		QueryResult queryresult = PersistenceHelper.manager.find(queryspec);
		WTContainer wtcontainer = null;
		while (queryresult.hasMoreElements()) {
			Object obj = queryresult.nextElement();
			if (obj instanceof WTContainer)
				wtcontainer = (WTContainer) obj;
		}
		return wtcontainer;
	}

	/**
	 * 通过number获取最新大版本物料
	 * 
	 * @param number
	 * @return
	 */

	public static List<WTPart> getAllLatestVersionPart(String number) {
		List<WTPart> list = new ArrayList<WTPart>();
		WTPart part = null;
		QuerySpec qs;
		try {
			qs = new QuerySpec(WTPart.class);
			SearchCondition sc = new SearchCondition(WTPart.class, WTPart.NUMBER, SearchCondition.EQUAL, number);
			qs.appendWhere(sc);
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
					new KeywordExpression("1")));
			qs.appendOrderBy(WTPart.class, "thePersistInfo.createStamp", true);
			QueryResult qr2 = PersistenceHelper.manager.find(qs);
			while (qr2.hasMoreElements()) {
				part = (WTPart) qr2.nextElement();
				wt.vc.VersionIdentifier vi = wt.vc.VersionControlHelper.nextVersionId(part);
				String v = vi.getValue();
				wt.part.WTPart p = MyPartUtil.getWTPartByNumViewAndVersion(part.getNumber(), part.getView().getName(),
						v);
				if (null != p) {
					continue;
				}
				list.add(part);
			}
		} catch (Exception e) {
		}
		return list;
	}

	public static void main(String[] args) throws IOException {
		// if (args == null || args.length != 1) {
		// return;
		// }
		// if (!RemoteMethodServer.ServerFlag) {
		// String method = "importHistoryDocuments";
		// try {
		//
		// logger.debug("Debug RemoteMethodServer...");
		// RemoteMethodServer.getDefault().invoke(method, CLASSNAME, null, new
		// Class[] { String.class }, new Object[] { args[0] });
		// logger.debug("Debug end RemoteMethodServer...");
		// } catch (RemoteException e) {
		// e.printStackTrace();
		// } catch (InvocationTargetException e) {
		// e.printStackTrace();
		// }
		// } else {
		// logger.debug("Debug importBoms...");
		// File file = new File("E:\\downLoadImportHistoryDocumentModel.xlsx");
		// if(file != null){
		// String fileNumber = file.getAbsolutePath();
		// if(fileNumber != null){
		// FileInputStream fis = null;
		// fis = new FileInputStream(fileNumber);
		// //Workbook wb = new HSSFWorkbook(fis);
		// Workbook wb = new XSSFWorkbook(fis);
		// StringBuffer strBuf = new StringBuffer();
		// Sheet sheet = wb.getSheetAt(0);
		// try {
		// importHistoryDocuments(sheet,strBuf);
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// }
		// }
		//
		// logger.debug("Debug end importBoms...");
		// }
	}

}
